package com.xu.modules.controller;

import cn.hutool.core.util.RandomUtil;
import com.xu.common.domain.MyResult;
import com.xu.common.enums.MailTypeEnum;
import com.xu.common.exception.MyException;
import com.xu.common.mail.MailDTO;
import com.xu.common.mail.MailService;
import com.xu.common.utils.RedisCache;
import com.xu.modules.service.PersonalUserService;
import com.xu.modules.service.bo.MailBo;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * 邮件控制器
 * @author xu
 * 2022/7/19 16:32
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/mail")
public class MailController {
    private final MailService mailService;
    public final RedisCache redisCache;
    public final PersonalUserService personalUserService;

    @PostMapping("/send")
    public MyResult send(@RequestBody @Valid MailBo mailBo){
        // 生成6位随机数
        int code = RandomUtil.randomInt(100000,999999);
        // 设置发送内容
        MailDTO mailDTO  = new MailDTO();
        // 设置发送人
        String mailFromUser = "xu_wang_9264@163.com";
        mailDTO.setFromUser(mailFromUser);
        // 发送给谁
        mailDTO.setToUser(mailBo.getEmail());
        // 发送内容
        String content = "";
        // 根据邮箱统计的
        Long countByEmail = personalUserService.countByEmail(mailBo.getEmail());
        // 如果是注册
        if(MailTypeEnum.REGISTER.getMailType().equals(mailBo.getType())){
            if(countByEmail>0){
                throw new MyException("该邮箱已注册!!!");
            }
            mailDTO.setSubject("xu的博客-注册");
            content = "您正在注册xu的博客,验证码为: " + code + " ,有效期为5分钟，请勿泄露给他人，祝您使用愉快！";
            String redisKey = mailBo.getEmail()+MailTypeEnum.REGISTER.getMailKey();
            redisCache.setCacheObject(redisKey,code);
            // 单位秒
            redisCache.expire(redisKey, 5 * 60);
        }
        // 如果是登录
        if(MailTypeEnum.LOGIN.getMailType().equals(mailBo.getType())){
            if(countByEmail==0){
                throw new MyException("还未注册!!!");
            }
            mailDTO.setSubject("xu的博客-登录");
            content = "您正在登录xu的博客,验证码为: " + code + " ,有效期为5分钟，请勿泄露给他人，祝您使用愉快！";
            String redisKey = mailBo.getEmail()+MailTypeEnum.LOGIN.getMailKey();
            redisCache.setCacheObject(redisKey,code);
            // 单位秒
            redisCache.expire(redisKey, 5 * 60);
        }
        // 设备发送的内容
        mailDTO.setText(content);

        // 发送
        CompletableFuture<Boolean> future = mailService.sendMail(mailDTO);
        // 发送失败报错
        if(future.complete(false)){
            throw new MyException("邮件发送失败，请检查邮箱");
        }
        return MyResult.ok();
    }
}
